﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using ESOL.Business.Mst;
using ESOL.Business.Sales;
using ESOL.Common;
using ESOL.Common.Entity;
using ESOL.WinUI.MasterData;
using ESOL.WinUI.Hr;
using ESOL.Business.Sec;

namespace ESOL.WinUI.Sales
{
    public partial class frmManageProductPlanApplicationOrder : BaseForm.frmBaseMdiBusinessForm
    {
        #region Variable
        private SalesProdPlanApplicationEntity mSelectedProdPlanApplication;
        #endregion

        #region Constructor
        public frmManageProductPlanApplicationOrder()
        {
            InitializeComponent();
        }
        #endregion

        #region Functions
        private void BindComboBox()
        {
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbStatus, "STATUS", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbApplicationType, "AT", true);
            UICommon.UICommonFunctions.BindComboboxByCommonItem(cmbProductType, "PTYPE", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colAPPLICATION_TYPE, "AT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPRODUCT_TYPE_ID, "PTYPE", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colSTATUS, "STATUS", true);

            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPACKAGE_TYPE, "PT", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colCHECKING_TYPE, "CHECK", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colSTATUS_ITEM, "PASTATUS", true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPRODUCT_TYPE, "AT", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colDELIVERY_APPLICATION, "DA", false);
            //UICommon.UICommonFunctions.BindGridComboboxByLocation(colLOCATION_CODE, "", true);
            UICommon.UICommonFunctions.BindGridComboboxByEnum(colPRINT_BRAND, typeof(BoolStatus), typeof(int), true);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colPRICE_TYPE, "PRICET", false);
            UICommon.UICommonFunctions.BindGridComboboxByCommonItem(colUNIT, "UNIT", true);

            colAPPLICATION_TYPE.NullText = "";
            colPRODUCT_TYPE_ID.NullText = "";
            colSTATUS.NullText = "";
            colPACKAGE_TYPE.NullText = "";
            colCHECKING_TYPE.NullText = "";
            colSTATUS_ITEM.NullText = "";
            colPRODUCT_TYPE.NullText = "";
            colDELIVERY_APPLICATION.NullText = "";
            colPRINT_BRAND.NullText = "";
            colPRICE_TYPE.NullText = "";
            colUNIT.NullText = "";

        }

        private string GetCondition()
        {
            string condition = "";
            if (txtSalesOrder.Tag != null && txtSalesOrder.Tag.GetType() == typeof(SalesOrderEntity))
            {
                SalesOrderEntity order = (SalesOrderEntity)txtSalesOrder.Tag;
                condition += " AND PPA.ORDER_ID = '" + order.OrderId + "' ";
            }
            if (txtCustomer.Tag != null && txtCustomer.Tag.GetType() == typeof(MstCustomerEntity))
            {
                MstCustomerEntity customer = (MstCustomerEntity)txtCustomer.Tag;
                condition += " AND PPA.CUSTOMER_ID = '" + customer.CustomerId + "' ";
            }
            if (string.IsNullOrEmpty(txtApplicationCode.Text) == false)
            {
                condition += " AND PPA.APPLICATION_CODE LIKE '%" + txtApplicationCode.Text + "%'";
            }
            if (dtpApplicationDate.EditValue!=null)
            {
                condition += " AND PPA.APPLICATION_DATE >= CONVERT(DATETIME,'" + ((DateTime)dtpApplicationDate.EditValue).ToString("yyyy-MM-dd HH:mm:ss") + "')";
            }
            if (dtpApplicationDateTo.EditValue!=null)
            {
                condition += " AND PPA.APPLICATION_DATE <= CONVERT(DATETIME,'" + ((DateTime)dtpApplicationDateTo.EditValue).ToString("yyyy-MM-dd HH:mm:ss") + "')";
            }
            if (dtpDeliveryDate.EditValue!=null && dtpDeliveryDateTo.EditValue!=null)
            {
                condition += @" AND PPA.APPLICATION_ID IN (SELECT APPLICATION_ID
                                    FROM SALES_PROD_PLAN_APPLICATION_ITEM
                                    WHERE REQUIRED_DELIVERY_DATE >= CONVERT(DATETIME,'" + ((DateTime)dtpDeliveryDate.EditValue).ToString("yyyy-MM-dd") + @"')
                                    AND REQUIRED_DELIVERY_DATE <= CONVERT(DATETIME,'" + ((DateTime)dtpDeliveryDateTo.EditValue).ToString("yyyy-MM-dd") + @"')
                                    GROUP BY APPLICATION_ID) ";
            }
            else if (dtpDeliveryDate.EditValue != null && dtpDeliveryDateTo.EditValue==null)
            {
                condition += @" AND PPA.APPLICATION_ID IN (SELECT APPLICATION_ID
                                    FROM SALES_PROD_PLAN_APPLICATION_ITEM
                                    WHERE REQUIRED_DELIVERY_DATE >= CONVERT(DATETIME,'" + ((DateTime)dtpDeliveryDate.EditValue).ToString("yyyy-MM-dd") + @"')
                                    GROUP BY APPLICATION_ID) ";
            }
            else if (dtpDeliveryDate.EditValue==null && dtpDeliveryDateTo.EditValue!=null)
            {
                condition += @" AND PPA.APPLICATION_ID IN (SELECT APPLICATION_ID
                                    FROM SALES_PROD_PLAN_APPLICATION_ITEM
                                    WHERE REQUIRED_DELIVERY_DATE <= CONVERT(DATETIME,'" + ((DateTime)dtpDeliveryDateTo.EditValue).ToString("yyyy-MM-dd") + @"')
                                    GROUP BY APPLICATION_ID) ";
            }
            if (string.IsNullOrEmpty(cmbApplicationType.Text) == false && cmbApplicationType.SelectedValue != null)
            {
                condition += " AND PPA.APPLICATION_TYPE = '" + cmbApplicationType.SelectedValue.ToString() + "'";
            }
            if (string.IsNullOrEmpty(cmbProductType.Text) == false && cmbProductType.SelectedValue != null)
            {
                condition += " AND PPA.PRODUCT_TYPE = '" + cmbProductType.SelectedValue.ToString() + "'";
            }
            if (string.IsNullOrEmpty(cmbStatus.Text) == false && cmbStatus.SelectedValue != null)
            {
                condition += " AND PPA.STATUS = '" + cmbStatus.SelectedValue.ToString() + "'";
            }
            
            List<MstCustomerEntity> customers = new List<MstCustomerEntity>();
            //获得用户对应的角色的所有子角色
            SecUserEntity user = ESOL.Business.Sec.SecUserBs.GetUserByID(Common.CommonParameter.CurrentUser.UserId);
            List<SecUserRoleEntity> userroles = SecUserRoleBs.GetSecUserRolesByUserID(user.UserId);
            List<SecRoleEntity> roles = new List<SecRoleEntity>();
            foreach (SecUserRoleEntity userrole in userroles)
            {
                roles.AddRange(SecRoleBs.GetChildrenRolesForID(userrole.RoleId, null));
            }
            //根据子角色获取所有对应的用户
            List<MstPersonEntity> persons = new List<MstPersonEntity>();
            if (roles.Count != 0)
            {
                persons = MstPersonBs.GetPersonForRoles(roles);
            }
            persons.Add(Common.CommonParameter.CurrentUser.PersonEntity);
            customers = MstPersonCustomerBs.GetCustomerByPersons(persons);
            if (customers.Count == 0)
                return condition;
            condition += " AND PPA.CUSTOMER_ID IN (";
            foreach (MstCustomerEntity m in customers)
            {
                condition += "'" + m.CustomerId + "',";
            }
            condition = condition.Substring(0, condition.Length - 1);
            condition += ")";
            if (txtApplicationPerson.Tag != null && txtApplicationPerson.Tag.GetType() == typeof(MstPersonEntity))
            {
                MstPersonEntity entity = (MstPersonEntity)txtApplicationPerson.Tag;
                condition += " AND PPA.APPLICATION_PERSON = '" + entity.PersonId + "' ";
            }
            else
            {
                condition += " AND PPA.APPLICATION_PERSON IN (";
                foreach (MstPersonEntity person in persons)
                {
                    condition += "'" + person.PersonId + "',";
                }
                condition = condition.Substring(0, condition.Length - 1);
                condition += ")";
            }

            return condition;
        }

        private void BindDataGrid()
        {
            string condition = GetCondition();
            string rowCount = txtRowCount.Text;
            string orderBy = "APPLICATION_CODE DESC";
            DataTable dt = SalesProdPlanApplicationBs.GetByCondition(condition, orderBy, rowCount);
            gvMain.DataSource = dt;
        }

        private void BindDetailGrid(string appID)
        {
            if (string.IsNullOrEmpty(appID))
            {
                gvDetail.DataSource = null;
                return;
            }
            DataSet ds = SalesProdPlanApplicationItemBs.GetDataSetByAppID(appID);
            if (ds == null || ds.Tables.Count == 0)
            {
                gvDetail.DataSource = null;
            }
            gvDetail.DataSource = ds.Tables[0];
        }

        private void ResetButtonsEnable()
        {
            btnModify.Enabled = false;
            btnDelete.Enabled = false;
            btnSubmit.Enabled = false;
            btnApprove.Enabled = false;
            //btnPreReceived.Enabled = false;
            if (mSelectedProdPlanApplication == null)
            {
                return;
            }
            if (mSelectedProdPlanApplication.Status == NormalStatus.STATUS01.ToString()
                || mSelectedProdPlanApplication.Status == NormalStatus.STATUS04.ToString())
            {
                btnModify.Enabled = true;
                btnDelete.Enabled = true;
                btnSubmit.Enabled = true;
                btnApprove.Enabled = true;
            }
            else if (mSelectedProdPlanApplication.Status == NormalStatus.STATUS02.ToString())
            {
                btnApprove.Enabled = true;
                btnModify.Enabled = true;
                btnDelete.Enabled = true;
            }
            else if (mSelectedProdPlanApplication.Status == NormalStatus.STATUS03.ToString())
            {
                btnPreReceived.Enabled = true;
            }
            else if (mSelectedProdPlanApplication.Status == NormalStatus.STATUS05.ToString())
            {
            }
        }
        #endregion

        #region Event
        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);
            mCanQueryOtherPerson = UICommon.UICommonFunctions.CheckPersonRight(RoleCategory.销售);
            BindComboBox();
            BindDataGrid();
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow dr = gridView1.GetDataRow(e.RowHandle);
            mSelectedProdPlanApplication = new SalesProdPlanApplicationEntity(dr);
            BindDetailGrid(mSelectedProdPlanApplication.ApplicationId);
            ResetButtonsEnable();
        }

        private void txtSalesOrder_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainSalesOrderQuery frm = new frmMaintainSalesOrderQuery();
            frm.IsOnlyApproved = true;
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedSalesOrder != null)
            {
                txtSalesOrder.Text = frm.SelectedSalesOrder.OrderCode;
                txtSalesOrder.Tag = frm.SelectedSalesOrder;
            }
            else
            {
                txtSalesOrder.Text = "";
                txtSalesOrder.Tag = null;
            }
        }

        private void txtApplicationPerson_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainEmployeeQuery frm = new frmMaintainEmployeeQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedPerson != null)
            {
                txtApplicationPerson.Text = frm.SelectedPerson.NameCn;
                txtApplicationPerson.Tag = frm.SelectedPerson;
            }
            else
            {
                txtApplicationPerson.Text = "";
                txtApplicationPerson.Tag = null;
            }
        }

        private void txtCustomer_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmMaintainCustomerQuery frm = new frmMaintainCustomerQuery();
            if (frm.ShowDialog() == DialogResult.OK && frm.SelectedCustomer != null)
            {
                txtCustomer.Text = frm.SelectedCustomer.CustomerName;
                txtCustomer.Tag = frm.SelectedCustomer;
            }
            else
            {
                txtCustomer.Text = "";
                txtCustomer.Tag = null;
            }
        }

        protected override void Click_Query()
        {
            BindDataGrid();
        }

        protected override void Click_View()
        {
            if (mSelectedProdPlanApplication == null)
            {
                MessageBox.Show("请选择一个生产计划申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainProductPlanApplicationOrder frm = new frmMaintainProductPlanApplicationOrder();
            frm.ThisActionType = ActionType.View;
            frm.SelectedProdPlanApplication = mSelectedProdPlanApplication;
            frm.ShowDialog();
        }

        protected override void Click_Delete()
        {
            if (mSelectedProdPlanApplication == null)
            {
                MessageBox.Show("请选择一个生产计划申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("是否删除选中生产计划申请单？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                return;
            }
            try
            {
                mSelectedProdPlanApplication.Status = NormalStatus.STATUS05.ToString();
                mSelectedProdPlanApplication.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mSelectedProdPlanApplication.LastModifiedDate = DateTime.Now;
                bool successful = SalesProdPlanApplicationBs.UpdateSalesProdPlanApplication(mSelectedProdPlanApplication);
                if (successful)
                {
                    MessageBox.Show("删除成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        protected override void Click_Submit()
        {
            if (mSelectedProdPlanApplication == null)
            {
                MessageBox.Show("请选择一个生产计划申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            DialogResult dr = MessageBox.Show("是否送审选中生产计划申请单？", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.No)
            {
                return;
            }
            try
            {
                mSelectedProdPlanApplication.Status = NormalStatus.STATUS02.ToString();
                mSelectedProdPlanApplication.LastModifiedBy = CommonParameter.CurrentUser.PersonId;
                mSelectedProdPlanApplication.LastModifiedDate = DateTime.Now;
                bool successful = SalesProdPlanApplicationBs.UpdateSalesProdPlanApplication(mSelectedProdPlanApplication);
                if (successful)
                {
                    MessageBox.Show("送审成功！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    BindDataGrid();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        protected override void Click_Approve()
        {
            if (mSelectedProdPlanApplication == null)
            {
                MessageBox.Show("请选择一个生产计划申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainProductPlanApplicationOrder frm = new frmMaintainProductPlanApplicationOrder();
            frm.ThisActionType = ActionType.Approve;
            frm.SelectedProdPlanApplication = mSelectedProdPlanApplication;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_Modify()
        {
            if (mSelectedProdPlanApplication == null)
            {
                MessageBox.Show("请选择一个生产计划申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            frmMaintainProductPlanApplicationOrder frm = new frmMaintainProductPlanApplicationOrder();
            frm.ThisActionType = ActionType.Modify;
            frm.SelectedProdPlanApplication = mSelectedProdPlanApplication;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        protected override void Click_New()
        {
            frmMaintainProductPlanApplicationOrder frm = new frmMaintainProductPlanApplicationOrder();
            frm.ThisActionType = ActionType.New;
            DialogResult dr = frm.ShowDialog();
            if (dr == System.Windows.Forms.DialogResult.OK)
            {
                BindDataGrid();
            }
        }

        private void btnPreReceived_Click(object sender, EventArgs e)
        {
            if (mSelectedProdPlanApplication == null)
            {
                MessageBox.Show("请选择一个生产计划申请单！", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            Finance.frmMaintainARRequest frm = new Finance.frmMaintainARRequest();
            frm.SalesProdPlanOrderCode = mSelectedProdPlanApplication.ApplicationCode;
            frm.OrderType = "RATYPE02";
            frm.ThisActionType = ActionType.New;
            frm.ShowDialog();
        }
        #endregion

    }
}
